<script setup lang="ts">
import { ElPageHeader } from 'element-plus'
import ViewTree from '../ViewTree/ViewTree.vue'
import ViewManage from '../ViewManage/ViewManage.vue'
import FullscreenModal from '@/components/FullscreenModal/FullscreenModal.vue'

import emitter from '@/bus'
import DictionaryPicker from '@/components/DictionaryPicker/DictionaryPicker.vue'

import { modelConfigApi } from '@/api'

const show = ref(false)
const hideTree = ref(false)

const content = ref('绑定应用模型')
const appModal = ref('1')

const isBinding = computed(() => {
  return !hideTree.value
})

const viewManageRef
  = ref<InstanceType<typeof ViewManage>>()

interface ModelConfig {
  modelType: string
  pointId?: number
  indicatorIds: (number | undefined)[]
}
async function bindData(data: Required<ModelConfig>) {
  try {
    const { code } = await modelConfigApi.addModelConfig(
      data,
    )
    if (code === 200) {
      show.value = false
      ElMessage.success('保存成功')
    }
  }
  catch (e) {}
}
async function unbindData(data: ModelConfig) {
  try {
    const { code } = await modelConfigApi.updateModelConfig(
      data,
    )
    if (code === 200) {
      show.value = false
      ElMessage.success('保存成功')
    }
  }
  catch (e) {}
}

function clickSave() {
  const checked = viewManageRef.value?.checked || []
  const indicator = checked[0]
  const pointId = indicator?.id
  const indicatorIds = checked.map(v => v.id)
  const modelType = appModal.value

  // console.log(`isBinding: ${isBinding.value}`);
  // console.log(`pointId: ${pointId}`);
  // console.log(`modelType: ${modelType}`);
  // console.log(`indicatorIds: ${indicatorIds}`);

  if (isBinding.value) {
    if (
      pointId === undefined
      || indicatorIds.length === 0
    ) {
      ElMessage.error('请勾选指标进行应用建模')
      return
    }
    // console.log('bind');
    bindData({
      pointId,
      modelType,
      indicatorIds,
    })
  }
  else {
    // console.log('unbind');
    unbindData({
      pointId,
      modelType,
      indicatorIds,
    })
  }
}

function changeHandler() {
  emitter.emit(
    'query:app-model-indicators',
    appModal.value,
  )
}

onBeforeUnmount(() => {
  emitter.off('show:bind-app-modal')
})
onMounted(() => {
  emitter.on('show:bind-app-modal', (e) => {
    if (e) {
      content.value = '解绑应用模型'
    }
    else {
      content.value = '绑定应用模型'
    }
    hideTree.value = e
    show.value = true
  })
})
</script>

<template>
  <FullscreenModal v-model="show">
    <div class="width-fill heigh-fill flex-direction flex">
      <ElPageHeader
        class="margin-bottom-sm"
        title="返回"
        :content="content"
        @back="show = false"
      >
        <template #extra>
          <ElForm inline>
            <ElFormItem
              label="选择应用模型"
              style="margin-bottom: 0"
            >
              <DictionaryPicker
                v-model="appModal"
                code="YING_YONG_MO_XING"
                @change="changeHandler"
              />
            </ElFormItem>
            <ElFormItem
              style="margin-bottom: 0; margin-right: 0"
            >
              <ElButton type="primary" @click="clickSave">
                保存
              </ElButton>
            </ElFormItem>
          </ElForm>
        </template>
      </ElPageHeader>
      <BScrollbar>
        <div
          class="heigh-fill flex-fillRemaining align-center relative box-border flex"
        >
          <ViewTree v-if="!hideTree" readonly />
          <ViewManage
            ref="viewManageRef"
            show-checkbox
            :show-buttons="false"
          />
        </div>
      </BScrollbar>
    </div>
  </FullscreenModal>
</template>
